package controller;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;

import model.SubmittedData;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import utils.Utils;
import utils.XmlParser;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import app.cloudstringers.All;
import app.cloudstringers.MyVideoTab;
import define.API;
import define.Constants;

public class AddItemAsync extends AsyncTask<SubmittedData, Void, Boolean> {

	/**
	 * Data section
	 */
	
	/**
	 * String section
	 */
	private boolean IS_ERROR = false;

	private String ERROR = null;
	private String KEY_ERROR = "error";
	private String KEY_ROOT = "root";

	private static final String TAG = AddItemAsync.class.getSimpleName();

	/**
	 * The others section
	 */
	private Utils connectivity;
	private Context context;

	public AddItemAsync(Context context) {
		connectivity = new Utils(context);

		this.context = context;
	}

	@Override
	protected Boolean doInBackground(SubmittedData... submitedData) {
		HttpClient mHttpClient = new DefaultHttpClient();
		
		/**
		 * .getTags()  might be is duplicate value,
		 * should check not duplicate in here
		 */
		String URL = API.ADD_ITEM + GetTokenString.TOKEN_STRING + "&video="
				+ submitedData[0].getItemID() + "&sales_type="
				+ submitedData[0].getSaleType() + "&title=" + submitedData[0].getTitle()
				+ "&desc=" + submitedData[0].getDescription().replace(" ", "%20")
				+ "&tags=" + Utils.removeDuplicatesInString(submitedData[0].getTags()) + "&country_id="
				+ submitedData[0].getCountryID();
		if (submitedData[0].getAuctionPeriod() != null
				&& !submitedData[0].getAuctionPeriod().equals("")) {
			/**
			 * Auction collection
			 */
			if (submitedData[0].getSelling() == Constants.SELLING_AUCTION) {
				// If the item already existed on Market Place
				// Add "&edit=yes"
				// URL for send auction data to the server
				URL = URL + "&price=" + submitedData[0].getBasePrice()
						+ "&buy_now_price=" + submitedData[0].getBuyNowPrice()
						+ "&auction_period="
						+ submitedData[0].getAuctionPeriod().substring(0, 2) + "&city="
						+ submitedData[0].getCity() + "&camcorder_model="
						+ submitedData[0].getCamcorderModel() + "&journalist_ID="
						+ submitedData[0].getJournalistID() + "&association="
						+ submitedData[0].getAssociation() + "&edit=yes";
			} else {
				// URL for send auction data to the server
				URL = URL + "&price=" + submitedData[0].getBasePrice()
						+ "&buy_now_price=" + submitedData[0].getBuyNowPrice()
						+ "&auction_period="
						+ submitedData[0].getAuctionPeriod().substring(0, 2) + "&city="
						+ submitedData[0].getCity() + "&camcorder_model="
						+ submitedData[0].getCamcorderModel() + "&journalist_ID="
						+ submitedData[0].getJournalistID() + "&association="
						+ submitedData[0].getAssociation();
			}
		} else {
			/**
			 * Market Place collection
			 */
			if (submitedData[0].getSelling() == Constants.SELLING_MARKET_PLACE) {
				// If the item already existed on Market Place
				// Add "&edit=yes"

				// URL for send market place data to the server
				URL = URL + "&price=" + submitedData[0].getBasePrice() + "&city="
						+ submitedData[0].getCity() + "&camcorder_model="
						+ submitedData[0].getCamcorderModel() + "&journalist_ID="
						+ submitedData[0].getJournalistID() + "&association="
						+ submitedData[0].getAssociation() + "&edit=yes";
			} else {
				// If the item not already existed on Market Place
				// Not Add "&edit=yes"

				// URL for send market place data to the server
				URL = URL + "&price=" + submitedData[0].getBasePrice() + "&city="
						+ submitedData[0].getCity() + "&camcorder_model="
						+ submitedData[0].getCamcorderModel() + "&journalist_ID="
						+ submitedData[0].getJournalistID() + "&association="
						+ submitedData[0].getAssociation();
			}
		}

		// TODO
		Log.i(TAG, "" + URL);

		URI website;
		try {
			
			website = new URI(URL.replace(" ", "%20"));
			HttpGet request = new HttpGet();

			request.setURI(website);
			
			HttpResponse mHttpResponse = mHttpClient.execute(request);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();

			String XML = EntityUtils.toString(mHttpEntity);

			// TODO
			Log.i(TAG,  XML);

			XmlParser mXMLParser = new XmlParser();
			Document mDocument = mXMLParser.getDomElement(XML);

			// List element follow video_id key
			NodeList mNodeList = mDocument.getElementsByTagName(KEY_ROOT);
			for (int i = 0; i < mNodeList.getLength(); i++) {
				if (mNodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) mNodeList.item(i);

					// Notify the user this error message
					ERROR = mXMLParser.getValue(element, KEY_ERROR);

					if (!ERROR.equals("")) {
						IS_ERROR = true;

						return false;
					}
				}
			}
			return true;
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		// Show progress dialog
		connectivity.showProgressDialog();
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);

		if (!result) {
			if (IS_ERROR) {
				Toast.makeText(context, ERROR, Toast.LENGTH_SHORT).show();
			} else {
				connectivity.showConnectionTimeoutDialog(context, All.class);
			}
		} else {
			// Refresh
			new AllTabsAsync(context).execute(MyVideoTab.CURRENT_TAB);

			new GetTokenString(context, true).execute();
		}

		// Show progress dialog
		connectivity.hideProgressDialog();
	}
}
